import { markRaw } from 'vue'
import BaseLayout from '@/layout/base-layout.vue'
//eslint-disable-next-line
import { RouterView } from 'vue-router'
const autoImportPage = import.meta.glob(['@/views/**/index.vue'])
const autoImportPageInfo = import.meta.glob(['@/views/**/auto-route.js'], { eager: true })

// 使用 markRaw 包装 BaseLayout 和 RouterView 组件
const rawBaseLayout = markRaw(BaseLayout)
const rawRouterView = markRaw(RouterView)

let autoImportRotesCache = {}
let autoImportRotes = []

// 首先按路径深度排序，确保父路由先于子路由处理
const sortedPaths = Object.keys(autoImportPageInfo).sort((a, b) => {
  const depthA = a.split('/').length
  const depthB = b.split('/').length
  return depthA - depthB
})

for (let path of sortedPaths) {
  let pathList = path.split('/').slice(3, -1)
  let realPath = pathList.join('/')
  let route = {
    name: realPath,
    path: '/' + realPath,
    meta: {
      name: realPath
    },
    component: () => {
      const modulePath = `/src/views/${realPath}/index.vue`;
      const moduleImport = autoImportPage[modulePath];
      
      if (moduleImport) {
        return moduleImport();
      } else {
        // 检查是否有子路由，如果有则使用RouterView，否则返回404页面
        const hasChildren = Object.keys(autoImportPageInfo).some(p => {
          // 检查是否存在以当前路径开头的其他路径，表示有子目录
          return p !== path && p.startsWith(`/src/views/${realPath}/`);
        });
        
        if (hasChildren) {
          console.log(`路由 ${realPath} 没有index.vue但有子路由，使用RouterView`);
          return Promise.resolve(rawRouterView);
        } else {
          console.error(`路由组件不存在: ${modulePath}`);
          return import('@/views/page-404.vue');
        }
      }
    }
  }
  let info = autoImportPageInfo[path]
  if (info) {
    Object.assign(route, info.default)
  }
  autoImportRotesCache[pathList.join('/')] = route
  let parentRoute = autoImportRotesCache[pathList.slice(0, -1).join('/')]
  
  if (pathList.length > 1 && parentRoute) {
    parentRoute.children = parentRoute.children || []
    parentRoute.children.push(route)
    parentRoute.children.sort((a, b) => {
      return (b.weight || 0) - (a.weight || 0)
    })
  } else {
    autoImportRotes.push(route)
  }
}

autoImportRotes.push({
  path: '',
  weight: 100,
  meta: { name: '首页', icon: 'House' },
  component: () => import('@/views/home.vue')
})

autoImportRotes.sort((a, b) => {
  return (b.weight || 0) - (a.weight || 0)
})

export default [
  {
    path: '',
    name: 'root',
    component: rawBaseLayout,
    children: [...autoImportRotes]
  }
]